package cn.lsoft.undoner.service.impl;

import cn.lsoft.undoner.dao.MessageDao;
import cn.lsoft.undoner.model.MessageRequest;
import cn.lsoft.undoner.service.ScheduleService;
import cn.lsoft.undoner.util.DataTimeUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author <A HREF="mailto:undoner@gmail.com">undoner</A>
 * @date 11-25-2014
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    private static final Logger LOGGER = Logger.getLogger(ScheduleServiceImpl.class);
    public static final String TIMEZONE_ID = "UTC";

    //周日 到 周六 的 2 进制，用于判断周几需要录制
    public static final int[] WEEKS = {64, 1, 2, 4, 8, 16, 32};

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.message.queue}")
    private String messageQueue;

    @Qualifier("messageDaoImpl")
    @Autowired
    private MessageDao messageDao;

    private Gson gson;

    @PostConstruct
    public void init() {
        gson = new GsonBuilder().create();
    }

    @Scheduled(cron = "${message.create.queue.cron:0 1 * * * ?}")
    @Override
    public void createQueque() {
        MessageRequest messageRequest =new MessageRequest();
        messageRequest.setRequestUuid(UUID.randomUUID().toString());
        messageRequest.setContent("内容：" + String.valueOf(System.currentTimeMillis()));
        messageRequest.setStatus(1);
        messageRequest.setRequestTime(DataTimeUtils.getCurrentTime());
        sendRecord(messageRequest);
    }

    @Scheduled(cron = "${message.query.queue.cron:0 1 * * * ?}")
    @Override
    public void queryQueque() {
        List<MessageRequest> messageList = messageDao.queryMessageList();
        System.out.println(gson.toJson(messageList));
    }


    private void sendRecord(MessageRequest messageRequest) {
        rabbitTemplate.convertAndSend(messageQueue, gson.toJson(messageRequest));
        LOGGER.debug("send Queue_Success,uuid:" + messageRequest.getRequestUuid());
    }

}
